/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.py.net.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import com.google.protobuf.MessageLite;
import com.py.net.client.input.CmdRoute;
import com.py.net.client.input.IInputBuilder;
import com.py.net.proto.ProtoMapper;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Simple SSL chat client modified from {@link TelnetClient}.
 */
public final class Client {

    static final String HOST = System.getProperty("host", "127.0.0.1");
    static final int PORT = Integer.parseInt(System.getProperty("port", "8992"));

    public static void main(String[] args) throws Exception {
    	ProtoMapper.init();
    	CmdRoute.init();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .handler(new ClientInitializer());

            // Start the connection attempt.
            Channel ch = b.connect(HOST, PORT).sync().channel();

            // Read commands from the stdin.
            ChannelFuture lastWriteFuture = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            for (;;) {
                String line = in.readLine();
                if (line == null) {
                    break;
                }

                if ("bye".equals(line.toLowerCase())) {
                	ch.close().sync();
                    break;
                }
                
                MessageLite msg = buildMsg(line);
                if (msg != null) {
                	lastWriteFuture = ch.writeAndFlush(msg);
				}
            }

            // Wait until all messages are flushed before closing the channel.
            if (lastWriteFuture != null) {
                lastWriteFuture.sync();
            }
        } finally {
            // The connection is closed automatically on shutdown.
            group.shutdownGracefully();
        }
    }
    
    private static MessageLite buildMsg(String line) {
    	int index = line.indexOf(":");
    	if (index > 0) {
    		IInputBuilder inputBuilder = CmdRoute.getInputBuilder(line.substring(0, index));
    		if (inputBuilder != null) {
    			MessageLite msg = inputBuilder.builder(line.substring(index + 1));
				return msg;
			}
    	}
		System.out.println("未注册的命令!");
    	return null;
    }
}
